package com.faker.core.jdbc;


import com.alibaba.druid.pool.DruidDataSource;
import com.faker.entity.SysConnection;
import com.faker.service.ConnectionManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.Map;

/**
 * 切换数据源
 */
@Component
@Slf4j
public class DataSourceChange {
    private static ConnectionManagerService connectionManagerService;

    @Resource
    ConnectionManagerService connectionManagerServiceBean;


    /**
     * 初始化静态Bean
     */
    @PostConstruct
    public void initBean() {
        connectionManagerService = connectionManagerServiceBean;
    }


    /**
     * 切换数据源为默认：Sqlite
     */
    public static void changeDataSource() {
        log.info("切换数据源：default");
        DataSourceContextHolder.setDataSourceType("default");

    }


    /**
     * 切换数据源
     * 注意：切换数据源一定要在事务之前，否则可能会引发报错
     */
    public static void changeDataSource(Long connectionId) {
        String key = connectionId.toString();
        log.info("切换数据源：" + key);
        Map<Object, Object> dataSourceMap = DynamicDataSource.getInstance().getDataSourceMap();
        if (!dataSourceMap.containsKey(key)) {
            SysConnection sysConnection = connectionManagerService.findConnectionById(connectionId);
            log.info("Druid连接池添加：" + sysConnection.toString());
            DruidDataSource dynamicDataSource = new DruidDataSource();
            try {
                dynamicDataSource.setFilters("stat,wall,slf4j");
            } catch (SQLException e) {
                log.error("数据源添加Filters失败");
            }
            // 缺省DriverClassName时，Druid会自动匹配
            // dynamicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
            dynamicDataSource.setUrl(sysConnection.getUrl());
            dynamicDataSource.setUsername(sysConnection.getUsername());
            dynamicDataSource.setPassword(sysConnection.getPassword());

            dynamicDataSource.setTestWhileIdle(false);
            dataSourceMap.put(key, dynamicDataSource);
            DynamicDataSource.getInstance().setTargetDataSources(dataSourceMap);
            //切换为动态数据源实例
            DataSourceContextHolder.setDataSourceType(key);
        } else {
            //切换为动态数据源实例
            DataSourceContextHolder.setDataSourceType(key);
        }
    }


}

